﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using EOSCRM.Domain;
using EOSCRM.Util;


namespace EOSCRM.Dao
{
    public  class BanDao : BaseDao
    {
        public BAN   Get(string ma)
        {
            return _db.BANs.SingleOrDefault(p => p.MaBan .Equals(ma));
        }


        public List<BAN> Search(string key)
        {
            return _db.BANs.Where(p => p.MaBan .ToUpper().Contains(key.ToUpper())).ToList();
        }
        public List<BAN> GetList()
        {
            return _db.BANs.ToList();
        }
     
        public List<BAN> GetList(string malo, DateTime ngay)
        {
            return _db.BANs.Where(p=>p.MaLo.Equals(malo) & p.NgayBan.Equals(ngay.Date)).ToList();
        }

        public List<BAN> GetList(int fromIndex, int toIndex)
        {
            return GetList().Skip(fromIndex).Take(toIndex - fromIndex).ToList();
        }

        public int Count( )
        {
            return _db.BANs.Count();
        }

        public Message Insert(BAN objUi, String ComputerName, String IpAdress, String smanv)
        {
            Message msg;
            try
            {

                _db.Connection.Open();

                _db.BANs.InsertOnSubmit(objUi);
                _db.SubmitChanges();
                #region luuvet
                var luuvet = new LUUVET_KYDUYET
                {
                    MADON = objUi.MaBan,
                    MANV = smanv,
                    IPAddress = IpAdress,
                    MATT = TACVUKYDUYET.I.ToString(),
                    MOTA = "Bán mũ cao su",
                    NGAYTHUCHIEN = DateTime.Now,
                    TACVU = TACVUKYDUYET.I.ToString(),
                    UserAgent = ComputerName,
                    LOAIDON = "",
                    MACN = "",
                };
                _db.LUUVET_KYDUYETs.InsertOnSubmit(luuvet);
                _db.SubmitChanges();
                #endregion
                // commit

                // success message
                msg = new Message(MessageConstants.I_CREATE_SUCCEED, MessageType.Info, "bán cao su");

                LoDao _loDao = new LoDao();
                _loDao.UpdateTruLuong(objUi.MaLo,- decimal.Parse(objUi.KhoiLuong.ToString()));
            }
            catch (Exception ex)
            {
                // rollback transaction

                msg = ExceptionHandler.HandleInsertException(ex, "bán cao su", objUi.MaBan);
            }
            return msg;
        }

        public Message Update(BAN objUi, String ComputerName, String IpAdress, String smanv)
        {
            Message msg;
            try
            {
                // get current object in database
                var objDb = Get(objUi.MaBan     );

                if (objDb != null)
                {
                    //TODO: update all fields
                    decimal cu = decimal.Parse(objDb.KhoiLuong.ToString());
                    objDb.Gia = objUi.Gia;
                    objDb.KhoiLuong = objUi.KhoiLuong;
                    objDb.TongTien = objUi.TongTien;
                    objDb.MaLo = objUi.MaLo;
                       // Submit changes to db
                    _db.SubmitChanges();
                    #region luuvet
                    var luuvet = new LUUVET_KYDUYET
                    {
                        MADON = objUi.MaBan,
                        MANV = smanv,
                        IPAddress = IpAdress,
                        MATT = TACVUKYDUYET.U.ToString(),
                        MOTA = "Cập nhật bán mũ cao su",
                        NGAYTHUCHIEN = DateTime.Now,
                        TACVU = TACVUKYDUYET.I.ToString(),
                        UserAgent = ComputerName,
                        LOAIDON = "",
                        MACN = "",
                    };
                    _db.LUUVET_KYDUYETs.InsertOnSubmit(luuvet);
                    _db.SubmitChanges();
                    #endregion
                    LoDao _loDao = new LoDao();
                    _loDao.UpdateTruLuong(objDb.MaLo, cu - decimal.Parse(objUi.KhoiLuong.ToString()));

                    // success message
                    msg = new Message(MessageConstants.I_UPDATE_SUCCEED, MessageType.Info, "bán cao su");
                }
                else
                {
                    // error message
                    msg = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Error, "bán cao su", objUi.MaBan);
                }
            }
            catch (Exception ex)
            {
                msg = ExceptionHandler.HandleUpdateException(ex, "bán cao su", objUi.MaBan);
            }
            return msg;
        }

        public bool IsInUse(string ma)
        {
            
            return false;
        }

        public Message Delete(BAN objUi, String ComputerName, String IpAdress, String smanv)
        {
            Message msg;

            try
            {
                // Get current Item in db
                var objDb = Get(objUi.MaBan   );

                if (objDb == null)
                {
                    // error message
                    msg = new Message(MessageConstants.E_OBJECT_NOT_EXISTS, MessageType.Error, "Bán cao su", objUi.MaBan      );
                    return msg;
                }

                //TODO: check if "hồ sơ đất" is in use

                // Set delete info
                _db.BANs.DeleteOnSubmit(objDb);
                // Submit changes to db
                _db.SubmitChanges();
                #region luuvet
                var luuvet = new LUUVET_KYDUYET
                {
                    MADON = objUi.MaBan,
                    MANV = smanv,
                    IPAddress = IpAdress,
                    MATT = TACVUKYDUYET.D.ToString(),
                    MOTA = "Xóa bán mũ cao su",
                    NGAYTHUCHIEN = DateTime.Now,
                    TACVU = TACVUKYDUYET.I.ToString(),
                    UserAgent = ComputerName,
                    LOAIDON = "",
                    MACN = "",
                };
                _db.LUUVET_KYDUYETs.InsertOnSubmit(luuvet);
                _db.SubmitChanges();
                #endregion
                // success message
                msg = new Message(MessageConstants.I_DELETE_SUCCEED, MessageType.Info, "Bán cao su ");
            }
            catch (Exception ex)
            {
                msg = ExceptionHandler.HandleDeleteException(ex, "Bán cao su ");
            }

            return msg;
        }

        public Message DeleteList(List<BAN> objList, String ComputerName, String IpAdress, String smanv)
        {
            Message msg;
            DbTransaction trans = null;

            try
            {
                _db.Connection.Open();
                trans = _db.Connection.BeginTransaction();
                _db.Transaction = trans;

                var failed = 0;

                foreach (var obj in objList)
                {
                    var temp = Delete(obj, ComputerName, IpAdress, smanv);
                    if (temp != null && temp.MsgType.Equals(MessageType.Error))
                    {
                        failed++;
                    }
                    else
                    {
                        LoDao _loDao = new LoDao();
                        _loDao.UpdateTruLuong(obj.MaLo, decimal.Parse(obj.KhoiLuong.ToString()));
                    }
                }

                // commit
                trans.Commit();

                if (failed > 0)
                {
                    if (failed == objList.Count)
                        return new Message(MessageConstants.E_DELETE_FAILED_EXCEPTION, MessageType.Info, "danh sách bán cao su");

                    var succeed = objList.Count - failed;
                    return new Message(MessageConstants.W_DELETELIST_SUCCEED_WITH_ERRORS, MessageType.Warning,
                                       succeed, "bán cao su", failed, "bán cao su");
                }
                // success message
                msg = new Message(MessageConstants.I_DELETE_SUCCEED, MessageType.Info, objList.Count + " bán cao su");
            }
            catch (Exception ex)
            {
                // rollback transaction
                if (trans != null)
                    trans.Rollback();

                msg = ExceptionHandler.HandleInsertException(ex, "danh sách bán cao su");
            }

            return msg;
        }

        
    }
}
